<?php
// $Id: zone.php 165 2012-02-02 03:02:18Z tomqin@gmail.com $

class Zone_Module{

	private $cityid = 0;
	private $data   = array();
	private $index  = array();
	private $pinyin = array();

	function __construct(){}

	function cacheName(){
		return 'system.zone.'.$this->cityid;
	}

	function initCity($cityid = 0){
		$this->cityid = intval($cityid ? $cityid : Config::get('default.cityid'));

		$cache = Cache::get($this->cacheName());
		if($cache){
			$this->data   = $cache['data'];
			$this->index  = $cache['index'];
			$this->pinyin = $cache['pinyin'];
		}
	}

	// @return array<stdClass>
	function getZoneList($id){
		$data = array();
		if(isset($this->index[$id])){
			foreach($this->index[$id] as $zid){
				$data[$zid] = $this->getZoneById($zid);
			}
		}
		return $data;
	}

 	// @return stdClass
	function getZoneById($id){
		if(isset($this->data[$id])){
			return $this->data[$id];
		}else{
			return null;
		}
	}

 	// @return stdClass
	function getZoneByPy($py){
		if(isset($this->pinyin[$py])){
			return $this->getZoneById($this->pinyin[$py]);
		}else{
			return null;
		}
	}

	function hasZone($id){
		return isset($this->index[$id]);
	}

	function makeCache(){
		Base::loadFunction('iconv');

		$zones = DB::getAll("select zone_id, parent_id, name, ename as pinyin, zone_type, display from `t_zone`
							where `city_id` = ? order by `ordnum`", array($this->cityid));

		$pinyin = $index = $data = array();
		foreach($zones as $z){
			if(!$z['pinyin']){
				$_name = iconv(CHARSET, 'GBK', $z['name']);
				$z['pinyin'] = join('', gbk_to_pinyin($_name));
			}
			$t = 0;
			while(array_key_exists($z['pinyin'], $pinyin)){
				$t++;
				$z['pinyin'] = $z['pinyin'].$t;
			}
			$pinyin[$z['pinyin']] = $z['zone_id'];
			$index[$z['parent_id']][] = $z['zone_id'];
			$data[$z['zone_id']] = (Object) $z;
		}
		$cache = array(
			'pinyin' => $pinyin,
			'index'  => $index,
			'data'   => $data,
		);

		Cache::set($this->cacheName(), $cache);
	}

	function getData(){
		return $this->data;
	}
}

?>